package org.obs.controller;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.directwebremoting.WebContext;
import org.directwebremoting.WebContextFactory;
import org.obs.service.RegistrationService;
import org.obs.service.UserService;

public class RegistrationController {

    private UserService userService;

    private RegistrationService registrationService;

    public RegistrationController(UserService userService,
            RegistrationService registrationService) {
        this.userService = userService;
        this.registrationService = registrationService;
    }

    public String getRegistrationView() throws Exception {
        WebContext webContext = WebContextFactory.get();
        return webContext
                .forwardToString("/WEB-INF/jsp/registration/registration-content.jspx");
    }
    
    public SampleBean getBean() {
        SampleBean bean = new SampleBean();
        bean.setP1("111");
        return bean;
    }

    public List<ElementData> register(ElementData firstName,
            ElementData lastName, ElementData secondName, ElementData nick,
            ElementData email, ElementData password) {

        List<ElementData> result = new ArrayList<ElementData>();

        if (StringUtils.isBlank(firstName.getData())) {
            firstName.error("Empty value");
            result.add(firstName);
        }
        if (StringUtils.isBlank(lastName.getData())) {
            lastName.error("Empty value");
            result.add(lastName);
        }
        if (!userService.isEmailUnique(email.getData())) {
            email.error("Not unique");
            result.add(email);
        }
        if (!userService.isNickUnique(nick.getData())) {
            nick.error("Not unique");
            result.add(nick);
        }

        if (result.isEmpty()) {
            registrationService.createUserRequest(firstName.getData(), lastName
                    .getData(), secondName.getData(), nick.getData(), email
                    .getData(), password.getData());
        }
        return null;
    }

}
